package org.jim.server.helper.cs;

import cn.hutool.core.collection.CollUtil;
import com.huiyun.project.common.core.constant.SecurityConstants;
import com.huiyun.project.common.core.util.fn.FunctionUtils;
import com.huiyun.project.im.server.client.feign.RemoteMessageService;
import lombok.extern.slf4j.Slf4j;
import org.jim.core.ImConst;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.cache.redis.RedisCacheManager;
import org.jim.core.helper.cs.ICsChatHelper;
import org.jim.core.helper.cs.ICsSessionHelper;
import org.jim.core.packets.pub.pojo.JimChatBody;
import org.jim.core.packets.cs.session.vo.JimCsMessageReq;
import org.jim.core.packets.cs.session.vo.JimCsMessageResp;
import org.jim.core.packets.cs.user.vo.UserMessageData;
import org.jim.core.utils.JsonKit;
import org.jim.core.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @FileName: UserServiceImpl
 * @Description:
 * @Author linjie
 * @Date 2020/7/3010:53 AM
 * @Version 4.0.0
 */
@Component
@Slf4j
public class CsChatHelperImpl implements ICsChatHelper, ImConst {

    @Autowired
    private RemoteMessageService remoteMessageService;

    @Autowired
    private ICsSessionHelper csSessionHelper;


    @Override
    public void writeDbMessage(JimChatBody chatBody) {
        //永久存储到mysql或者mongodb
        remoteMessageService.save(chatBody, SecurityConstants.FROM_IN);
    }

    @Override
    public void writeOfflineMessage(String timelineTable, String timelineId, JimChatBody chatBody) {
        double score = chatBody.getCreateTime();
        RedisCacheManager.getCache(timelineTable).sortSetPush(timelineId, score, chatBody);
    }



    //客服查询历史记录
    @Override
    public List<JimCsMessageResp> getCsHistoryMessage(String userId, String csUserId, Double beginTime, Double endTime, Integer offset, Integer count) {
        JimCsMessageReq req = new JimCsMessageReq();
        req.setUserId(userId);
        req.setCsUserId(csUserId);
        req.setBeginTime(beginTime);
        req.setEndTime(endTime);
        req.setPageNum(offset);
        req.setPageSize(count);
        req.setOperateType(ImConst.CS_OPERATE);
        List<JimCsMessageResp> list = FunctionUtils.getOkData(remoteMessageService.getMessage(req, SecurityConstants.FROM_IN));
        return list;
    }

    //客户查询历史记录
    @Override
    public List<JimCsMessageResp> getHistoryMessage(String userId, String csTenantId, Double beginTime, Double endTime, Integer offset, Integer count) {
//        List<JimChatBody> list = new ArrayList<>();
        //redis查询
//        String key = ImConst.STORE + ImConst.SUFFIX + ImConst.USER + ImConst.SUFFIX + userId + "_" + csTenantId;
//        try {
//            Set<String> dataSet = JedisTemplate.me().getJedis().zrangeByScore(key, Double.MIN_VALUE, Double.MAX_VALUE, offset, count);
//            if (dataSet != null) {
//                JimChatBody jimChatBody;
//                for (String s : dataSet) {
//                    jimChatBody = new JimChatBody();
//                    jimChatBody=JSON.parseObject(s, JimChatBody.class);
//                    list.add(jimChatBody);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //
        //        return list;
        //数据库查询
        JimCsMessageReq req = new JimCsMessageReq();
        req.setUserId(userId);
        req.setCsTenantId(csTenantId);
        req.setBeginTime(beginTime);
        req.setEndTime(endTime);
        req.setPageNum(offset);
        req.setPageSize(count);
        req.setOperateType(ImConst.USER_OPERATE);
        List<JimCsMessageResp> list = FunctionUtils.getOkData(remoteMessageService.getMessage(req, SecurityConstants.FROM_IN));
        return list;
    }

    /**
     * 用户端获取客服的离线消息
     *
     * @param userId     用户ID
     * @param csTenantId 商家租户ID
     * @return
     */
    @Override
    public UserMessageData getCsOfflineMessage(String userId, String csTenantId) {
        String key = KeyUtil.formatKey(MSG_KEY.CS_USER_OFFLINE,
                "csTenantId", csTenantId, "userId", userId);
        List<String> messageList = RedisCacheManager.getCache(PUSH).sortSetGetAll(key);
        List<JimChatBody> messageDataList = JsonKit.toArray(messageList, JimChatBody.class);
        RedisCacheManager.getCache(PUSH).remove(key);
        return buildCsResultMessage(new UserMessageData(userId), messageDataList);
    }
    @Override
    public UserMessageData getCsOfflineMessage(String userId) {
        UserMessageData messageData = new UserMessageData(userId);
        try {
            String key = KeyUtil.formatKey(MSG_KEY.CS_USER_OFFLINE, "userId", userId);
            Set<String> keys = JedisTemplate.me().keys(PUSH + SUFFIX + key);
            //获取好友离线消息;
            if (CollUtil.isNotEmpty(keys)) {
                List<JimChatBody> messageList = new ArrayList<JimChatBody>();
                Iterator<String> userKeyIterator = keys.iterator();
                while (userKeyIterator.hasNext()) {
                    String k = userKeyIterator.next();
                    //k = k.substring(k.indexOf(CS + SUFFIX));
                    List<String> messages = RedisCacheManager.getCache(PUSH).sortSetGetAll(k);
                    RedisCacheManager.getCache(PUSH).remove(k);
                    messageList.addAll(JsonKit.toArray(messages, JimChatBody.class));
                }
                buildCsResultMessage(messageData, messageList);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return messageData;
    }

    @Override
    public UserMessageData getOfflineMessage(String userId, String csTenantId) {
        return null;
    }

    @Override
    public UserMessageData getOfflineMessage(String csTenantId, String... userIds) {
        return null;
    }


    /**
     * 用户获取客服的消息
     *
     * @param userMessage
     * @param messages
     */
    public UserMessageData buildCsResultMessage(UserMessageData userMessage, List<JimChatBody> messages) {
        if (Objects.isNull(userMessage) || CollUtil.isEmpty(messages)) {
            return userMessage;
        }
        messages.forEach(chatBody -> {
            List<JimChatBody> friendMessages = userMessage.getFriends().get(chatBody.getCsTenantId());
            if (CollUtil.isEmpty(friendMessages)) {
                friendMessages = new ArrayList();
                userMessage.getFriends().put(chatBody.getCsTenantId(), friendMessages);
            }
            friendMessages.add(chatBody);
        });
        return userMessage;
    }


}
